//import RSA from '../dist/wx_rsa';
var httpUrl="http://testh5.nocarddata.com/"; //测试环境
 //var httpUrl="https://h5api.nocarddata.com/"; //正式环境
var appId="wxce85807ed3f02b6f"; //正式环境公众号APPID
var AppSecret="66d6e3942de6a66d43d2830d313d8fba";//正式环境公众号APPID
var imgHttp ="http://mapi.sb.run/files/"; //图片服务器
//var branchno = "0010440106";  //机构号
var branchno = "1380440106";  //测试环境机构号

var baseFunction={
	/**
	 * 网络请求
	 * @param {Object} url 
	 * @param {Object} data 参数
	 * @param {Object} successCB 成功回调
	 * @param {Object} errCB 失败回调
	 */
	netRequest:function(url,data,successCB,errCB){
		var that=this;
		data.model = "wx"; //手机型号
        data.version = "wx"; //版本
        data.branchno = this.encryption(branchno); //机构号
        data.address = ""; //地址  暂时先写死
        data.areaCode = "440100"; //地区编码 暂时先写死
		$.ajax({
			url:httpUrl+url,
			data:data,
			type:"post",
			success:function(res){
				if(successCB){
					res.data=that.decryption(res.data);
					successCB(res)
				}
			},
			err:function(res){
				if(errCB){
					res.data=that.decryption(res.data);
					errCB(res);
				}
			}
			
		})
	},

	/**
	 * 微信分享
	 * @param {Object} title 标题
	 * @param {Object} desc 文字说明
	 * @param {Object} link 链接
	 * @param {Object} imgUrl 图片
	 * @param {Object} callback 成功回调
	 */
	getWXConf:function(title,desc,link,imgUrl,callback){
		var url="commonNote_getSignByShareByApp"
		var data={
			share_url:window.location.href
		}
		this.netRequest(url,data,function(res){
			console.log(res);
			
            wx.config({
                debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
                appId: res.infos.appId, // 必填，公众号的唯一标识
                timestamp: res.infos.timeStamp, // 必填，生成签名的时间戳
                nonceStr: res.infos.nonceStr, // 必填，生成签名的随机串
                signature: res.infos.sdksignature,// 必填，签名，
                jsApiList: [
                    "onMenuShareTimeline",
                    "onMenuShareAppMessage",
                    "onMenuShareQQ",
                    "onMenuShareWeibo",
                    "onMenuShareQZone",
                    "startRecord",
                    "stopRecord",
                    "onVoiceRecordEnd",
                    "playVoice",
                    "pauseVoice",
                    "stopVoice",
                    "onVoicePlayEnd",
                    "uploadVoice",
                    "downloadVoice",
                    "chooseImage",
                    "previewImage",
                    "uploadImage",
                    "downloadImage",
                    "translateVoice",
                    "getNetworkType",
                    "openLocation",
                    "getLocation",
                    "hideOptionMenu",
                    "showOptionMenu",
                    "hideMenuItems",
                    "showMenuItems",
                    "hideAllNonBaseMenuItem",
                    "showAllNonBaseMenuItem",
                    "closeWindow",
                    "scanQRCode",
                    "chooseWXPay",
                    "openProductSpecificView",
                    "addCard",
                    "chooseCard",
                    "openCard",
                ] // 必填，需要使用的JS接口列表，所有JS接口列表见附录2
            });


            wx.ready(function(){
		        wx.onMenuShareTimeline({
		            title: title,
		            link: link,
		            imgUrl: imgUrl,
		            success: function (res) {
		                if(callback){
		                	callback(res);
		                }
		            },
		            cancel: function (res) {
		                
		            },
		            fail: function (res) {
		            }
		        });
		        wx.onMenuShareAppMessage({
		            title: title,
		            desc: desc, //文字说明
		            link: link,
		            imgUrl:imgUrl,
		            success: function (res) {
		                if(callback){
		                	callback(res);
		                }
		            },
		            cancel: function (res) {
		                
		            },
		        });
		        wx.onMenuShareQQ({
		            title: title,
		            desc: desc, //文字说明
		            link: link,
		            imgUrl: imgUrl,
		            success: function () {
		                if(callback){
		                	callback(res);
		                }
		            },
		            cancel: function () {
		               
		            }
		        });
		
		        wx.onMenuShareQZone({
		            title:title, // 分享标题
		            desc:desc, // 分享描述
		            link: link, // 分享链接
		            imgUrl: imgUrl,// 分享图标
		            success: function () {
		                if(callback){
		                	callback(res);
		                }
		            },
		            cancel: function () {
		                $(".template").css("display","none");
		            }
		        });

                // config信息验证后会执行ready方法，所有接口调用都必须在config接口获得结果之后，config是一个客户端的异步操作，所以如果需要在页面加载时就调用相关接口，则须把相关接口放在ready函数中调用来确保正确执行。对于用户触发时才调用的接口，则可以直接调用，不需要放在ready函数中。
            });

            wx.error(function(res){
                console.log('信息验证失败',res);
                if(cb2){
                    cb2();
                }
                // config信息验证失败会执行error函数，如签名过期导致验证失败，具体错误信息可以打开config的debug模式查看，也可以在返回的res参数中查看，对于SPA可以在这里更新签名。
            });

            wx.checkJsApi({
                jsApiList: ['chooseImage'], // 需要检测的JS接口列表，所有JS接口列表见附录2,
                success: function(res) {
                    console.log('判断当前客户端版本是否支持指定JS接口',res);
                    // 以键值对的形式返回，可用的api值true，不可用为false
                    // 如：{"checkResult":{"chooseImage":true},"errMsg":"checkJsApi:ok"}
                }
            });
		})
	},
	 /**
     *  获取url上面的字符串
     * @param name
     * @returns {null}
     */
    getval: function (name) {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
        var r = window.location.search.substr(1).match(reg);
        if (r != null) return unescape(r[2]);
        return "";
    },
    /**
     * 微信授权动态获取微信code
     */
    getCode: function (url) {
        var url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid='
            + appId
            + '&redirect_uri=' + encodeURIComponent(url?url:window.location.href)
            + '&response_type=code&scope=snsapi_userinfo&state=5623#wechat_redirect';
        window.location.replace(url);
    },
    /**
     * 微信授权静态获取微信code
     */
    staticStateGetCode: function (url) {
        var url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid='
            + appId
            + '&redirect_uri=' + encodeURIComponent(url?url:window.location.href)
            + '&response_type=code&scope=snsapi_base&state=5623#wechat_redirect';
        window.location.replace(url);
    },
    /**
     * 微信授权获取微信openid和userId等用户信息
     */
    getOpenId: function (callback) {
    		var that=this;
	    	var code = this.getval("code");
	    	if( code ){
	    		var url = 'login_wechatLoginByApp';
	            var data={
	            	code:code,
	            }
	            this.netRequest(url,data,function(res){
	            	if(res.status==0){  //授权失败
	            		var link = (window.location.href).split('&code')[0];
	            		that.getCode(link);
	            		return;
	            	}
		         	//console.log(res);
	            	window.localStorage.setItem("userInfo",JSON.stringify(res));
	            	//声明变量
	            	sessionid=res.sessionid;
					user_id=res.resultInfos.user_id;
					if(callback){
						callback(res);
					}
	            })
	       	}else{
	       		var userIfo=JSON.parse(window.localStorage.getItem("userInfo"));
	       		if(userIfo && userIfo.sessionid){ //本地有数据
	       			return;
	       		}
	            this.getCode();
	        }
    	
    },
	/**
	 * 格式化时间
	 * @param {Object} tiem  时间 （s）
	 */
	formattingTime:function(tiem){
		var hour=Math.floor(Number(tiem));
		var min=Math.floor(hour/60)<10?("0"+(Math.floor(hour/60))):Math.floor(hour/60);
		var s=Math.floor(hour%60)<10?("0"+(Math.floor(hour%60))):Math.floor(hour%60);
		return (min+":"+s);
	},
	
	/**
	 * 分享初始化
	 */
	shareInit:function(){
		var title="***";
    	var desc="***";
    	var imgUrl = (window.location.href).split('html/')[0] + "**.png";
    	var link = (window.location.href).split('html/')[0] + "html/index.html?current=1";
    	baseFunction.getWXConf(title,desc,link,imgUrl);
	},
	/**
	 * 生成验证码
	 */
	MathRand:function () { 
		var Num = "";
		for (var i = 0; i < 4; i++) {
		  Num += Math.floor(Math.random() * 10);
		}
		return Num;
	},
	/**
	 * 加密
	 * @param word 参数
	 */
	encryption:function(word){
		var key = CryptoJS.enc.Utf8.parse("Xo4eMjGzMuJX3HBJ");
		var srcs = CryptoJS.enc.Utf8.parse(word);
		var encrypted = CryptoJS.AES.encrypt(srcs, key, {mode:CryptoJS.mode.ECB,padding: CryptoJS.pad.Pkcs7});
		return encrypted.toString();
	},
	/**
	* 解密
	* @param word 参数
	*/
	decryption:function(word){
		var key = CryptoJS.enc.Utf8.parse("Xo4eMjGzMuJX3HBJ");
		var decrypt = CryptoJS.AES.decrypt(word, key, {mode:CryptoJS.mode.ECB,padding: CryptoJS.pad.Pkcs7});
		return CryptoJS.enc.Utf8.stringify(decrypt).toString();
	},
	/**
	 * 发送验证码
	 * 	@param obj 点击的对象
	 *  @param phone 手机号码
	 *  @param code 验证码
	 */
	sendCode:function(obj,phone,code){
		if (obj.html() !="获取验证码"){ //控制重复请求
			return;
		}
		var i=60;
		obj.html(i+"s后再试");
		var time=setInterval(function(){
			i--;
			obj.html(i+"s后再试");
			if(i==0){
				clearInterval(time);
				obj.html("获取验证码");
			}
		},1000);
		var data={
			msgType: "4002",
			mobile: this.encryption(phone),
			arg1: this.encryption(code),
		};
		baseFunction.netRequest("message",data,function(res){
			
			$(".prompt").html(res.message).show(0).delay(1000).hide(0);
		})
	},
	/**
	 * 从本地获取用户信息
	 */
	getUserInfo:function(){
		var userData=window.localStorage.getItem("appUserInfo");
		if(!userData){ //没有用户数据的时候  跳转去登录页
			window.location.href="homePage.html";
			return;
		}
		return userData;
	},
	/**
     * 获取url上面的参数
     */
    getUrlParameterValueByKey:function (key){
        var  beens= this.getParameters();
        for( var i=0;i<beens.length;i++){
               var been = beens[i].split("=");
             if(key==been[0]){return been[1];}	
        }
    },
    getCurrentUrl:function() {
        return window.location.href;
    },	
    getUrlParameter:function() {
	    var url =this.getCurrentUrl();
	    return  url.match(/\?/)? url.split('?')[1]:url;
    },
    getParameters:function(){
        var parames =this.getUrlParameter();	
        return  parames.split('&');
	},
	/**
	 * 验证用户是否实名制
	 */
	verifyingRealName:function(callback){
		var userData=this.getUserInfo();
		//不等于2 未实名认证   2  已实名认证
		var status =JSON.parse((JSON.parse(userData)).merch).status;
		if(status!=2){ //跳转去实名验证 (调用接口去人脸识别)
			$(".mask .tip").html("你还未实名认证，请先实名认证");
			$(".mask").show(0);
			var btn=document.querySelector(".mask .btn");
			var that=this;
			btn.onclick=function(){
				$(".loding").show(0);
				$(".mask").hide(0);
				var phone=JSON.parse((JSON.parse(userData)).user).loginName; //登录返回的用户名
				var data={
					userName:that.encryption(phone),
					returnUrl:window.btoa(window.location.href),
				}
				that.netRequest("faceAuth",data,function(res){
					$(".loding").hide(0);
					if(res.code==200){ //成功
						$(".loding").hide(0);
						window.location.href=JSON.parse(res.data).url;
					}
				})
			}
		}else{
			$(".loding").hide(0);
			if(callback){
				callback();
			}
		}

	},
	  /**
   * 获取账单日和还款日
   * @param billingDay 账单日
   * @param repaymentDate 还款日
   */
	getData: function (billingDay,repaymentDate){
		var billingDay = Number(billingDay);  //账单日
		var repaymentDate = Number(repaymentDate); //还款日
		var date = new Date();
		var month = date.getMonth() + 1; //当前月
		var currentDate = date.getDate(); //当前日
		if (billingDay > repaymentDate){
		if(currentDate>billingDay){
			return{
				billingDay: month+1 + "月" + billingDay + "日",
				repaymentDate: (month + 2) + "月" + repaymentDate+"日",
			}
		}else{
			if(currentDate==billingDay){
			return {
				billingDay: month  + "月" + billingDay + "日",
				repaymentDate: month +1 + "月" + repaymentDate + "日",
			}
			}else{
			return {
				billingDay: month  + "月" + billingDay + "日",
				repaymentDate: month+1  + "月" + repaymentDate + "日",
			}
			}
		}
		}else{//账单日小于还款日
		if (billingDay <= currentDate) {
			if(currentDate<=repaymentDate){
			return {
				billingDay: month + "月" + currentDate + "日",
				repaymentDate: month + "月" + repaymentDate + "日",
			}
			}else{
			return {
				billingDay: (month + 1) + "月" + billingDay + "日",
				repaymentDate: (month+1) + "月" + repaymentDate + "日",
			}
			}
		} else {
			return {
			billingDay: month + "月" + billingDay + "日",
			repaymentDate: month + "月" + repaymentDate + "日",
			}
		}
		}
	},

}

